package com.thh.design.sington;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

/**
 * @ClassName Example1
 * @Description 单例模式(例子1)
 * 日志写入
 * @Author thh
 * @Date 19:49 2021/01/13
 **/
public class Example1 {

    public static void main(String[] args) {
        //获得日志单例对象
        FileLogger logger = FileLogger.getInstance();
        logger.write("hell0");
        logger.write("你好！");
        logger.close();
    }


}


class FileLogger {
    private  String path = "C:\\Users\\King\\Desktop\\java设计模式\\log.txt";

    private FileOutputStream out = new FileOutputStream(path,true);


    private FileLogger() throws FileNotFoundException {
        System.out.println("这是一个单例模式！");
    }

    public void write(String msg){
        try {
            Calendar c= Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH)+1;
            int day = c.get(Calendar.DAY_OF_MONTH);
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            int second = c.get(Calendar.SECOND);
            String strTime = "";
            strTime = String.format( "time: %d-%02d-%02d %02d:%02d:%02d\r\n",year,month,day,hour,minute,second);
            String strContent ="content: \r\n"+msg+"\r\n";
            byte[] buf = null;
            out.write(strTime.getBytes("gbk"));
            buf = strContent.getBytes("gbk");
            out.write(buf);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close(){
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class My{
        // static  final FileLogger log = new FileLogger();
        // 这个代码会出现 Unhandled exception错误  实例化对象的时候 成员变量会报错
        // 所以才修改成了下面的代码 用static静态代码快抓取异常
        static FileLogger log;
        static {
            try {
                log = new FileLogger();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static FileLogger getInstance(){
        return My.log;
    }
}
